package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biomatch.domain.CardType;
import com.biomatch.dto.Pagination;
import com.biomatch.mapper.CardTypeMapper;
import com.biomatch.service.CardTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CardTypeServiceImpl implements CardTypeService {

    @Autowired
    CardTypeMapper cardTypeMapper;

    @Override
    public IPage<CardType> getAllTypeByPage(Pagination pagination) {
        Page<CardType> page = new Page<>(pagination.getCurrent(), pagination.getPageSize());
        return cardTypeMapper.selectPage(page, null);
    }

    @Override
    public List<CardType> getAll() {
        return cardTypeMapper.selectList(null);
    }

    @Override
    public CardType saveOrUpdate(CardType cardType) {
        if (cardType.getId() <= 0) {
            QueryWrapper<CardType> cardTypeQueryWrapper = new QueryWrapper<>();
            cardTypeQueryWrapper.eq("cardTypeName",cardType.getCardTypeName());
            if (cardTypeMapper.selectCount(cardTypeQueryWrapper) > 0) {
                return null;
            }
            else {
                String code = String.valueOf(new Date().getTime());
                cardType.setCardTypeId("ct"+code.substring(5,code.length()));
                cardTypeMapper.insert(cardType);
                return cardType;
            }
        } else {
            QueryWrapper<CardType> cardTypeQueryWrapper = new QueryWrapper<>();
            cardTypeQueryWrapper.eq("cardTypeName",cardType.getCardTypeName())
                    .ne("cardTypeId",cardType.getCardTypeId());
            if (cardTypeMapper.selectCount(cardTypeQueryWrapper) > 0) {
                return null;
            }
            else {
                cardTypeMapper.updateById(cardType);
                return cardType;
            }
        }
    }

    @Override
    public CardType delete(CardType cardType) {
        QueryWrapper<CardType> cardTypeQueryWrapper = new QueryWrapper<>();
        cardTypeQueryWrapper.eq("cardTypeId",cardType.getCardTypeId() );
        if (cardTypeMapper.selectCount(cardTypeQueryWrapper) > 0) {
            cardTypeMapper.deleteById(cardType.getId());
            return cardType;
        } else
        {
            return null;
        }
    }

}
